import { ref, h, onMounted, watch, onUnmounted } from 'vue';

export default {
  name: 'CHtml',
  props: {
    content: undefined,
    fontColor: undefined,
  },
  setup(props) {
    let iframeRef = ref(null);
    let timer = null;

    function setIframeHeight(count) {
      if (!iframeRef || !iframeRef.value) {
        return;
      }
      let iframe = iframeRef.value;
      let doc = iframe.contentDocument;
      let height = doc.body.scrollHeight;
      iframe.style.height = height + 'px';
      clearTimeout(timer);
      if (Number.isFinite(count) && count-- > 0) {
        timer = setTimeout(() => setIframeHeight(count), 100);
      }
    }

    onMounted(() => {
      let color = props.fontColor;
      if (!color) {
        let root = document.querySelector(':root');
        let style = root ? getComputedStyle(root) : null;
        color = style ? style.getPropertyValue('--color-text') : null;
      }
      let iframe = iframeRef.value;
      let doc = iframe.contentDocument;
      let styleEl = doc.createElement('style');
      styleEl.textContent = `
      html,body {
        width: 100%;
        height: unset;
        margin: 0;
        color: ${color || 'rgba(0, 0, 0, 0.88)'};
        overflow: hidden;
      }
      img {
        width: 100%;
      }
      ::-webkit-scrollbar {
        width: 10px;
        height: 10px;
        background: transparent;
      }
      ::-webkit-scrollbar-track {
        background: transparent;
      }
      ::-webkit-scrollbar-thumb {
        border-radius: 10px;
        border: 3px solid transparent;
        background: #f0f0f0;
        background-clip: padding-box;
      }
      ::-webkit-scrollbar-thumb:hover {
        background: #f0f0f0;
        border-color: #f0f0f0;
      }
      ::-webkit-scrollbar-corner {
        background: transparent;
      }`;
      doc.head.appendChild(styleEl);
      watch(
        () => props.content,
        (content) => {
          doc.body.innerHTML = content;
          setTimeout(() => setIframeHeight(5), 50);
        },
        { immediate: true }
      );
    });
    onUnmounted(() => {
      clearTimeout(timer);
      props = iframeRef = timer = null;
    });
    return () => {
      return h('iframe', {
        ref: iframeRef,
        style: { width: '100%', height: '100%', border: 'none' },
      });
    };
  },
};
